﻿using DBUtility;
using gfLibrary;
using IYAKASAPortal.Services;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UtilityHelper;

namespace IYAKASAPortal.Statistics
{
    public partial class TJ_JCXH : System.Web.UI.Page
    {
        private DbStoredProcedure m_dbStoreProcedure;
        private string m_checkType;
        private string m_startDate;
        private string m_endDate;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["CheckType"] != null && !string.IsNullOrEmpty(Request["CheckType"]))
            {
                m_checkType = Request["CheckType"].ToString().Substring(0,1);
            }

            if (!IsPostBack)
            {
                string d1 = string.Format("{0}", DateTime.Now.ToString("yyyy-MM-dd"));   //默认查询开始时间
                string d2 = string.Format("{0}", DateTime.Now.ToString("yyyy-MM-dd"));   //默认查询截止时间

                txtStart.Text = d1;
                txtEnd.Text = d2;
                btnSearch_Click(null, null);
            }
            else
            {
                SetSearchDate();
            }

            if (m_checkType == "Z")
            {
                TableTitle.InnerText = "成都弥荣科技发展有限公司--检测线分类合格率汇总表(综检)";
                lblTistle.Text = "检测线分类合格率汇总表(综检)";
            }
            else if (m_checkType == "P")
            {
                TableTitle.InnerText = "成都弥荣科技发展有限公司--检测线分类合格率汇总表(排放)";
                lblTistle.Text = "检测线分类合格率汇总表(排放)";
            }
            else
            {
                TableTitle.InnerText = "成都弥荣科技发展有限公司--检测线分类合格率汇总表(安检)";
                lblTistle.Text = "检测线分类合格率汇总表(安检)";
            }
            lblJGMC.Text = string.Format("机动车安全技术检验机构名称:{0}", StaInfoTools.GetStationName());

        }



        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="JCLSH">检测流水线号</param>
        /// <param name="logMsg">日志消息</param>
        /// <param name="operatorName">操作员名称</param>
        /// <param name="type">日志类型</param>
        /// <param name="funName">方法名称</param>
        //private void WriteLog(string JCLSH, string logMsg, string operatorName, LogHelper.LogType type, string funName)
        //{
        //    try
        //    {
        //        #region 日志记录
        //        LogHelper logHelper = LogHelper.GetSingleLogHelper();
        //        string strCategory = LogHelper.LogType.Normal.ToString();
        //        LOG_INFO logInfo = new LOG_INFO();
        //        logInfo.Category = strCategory;
        //        logInfo.HostName = System.Net.Dns.GetHostName();
        //        logInfo.IPAddress = System.Net.Dns.GetHostAddresses(logInfo.HostName).GetValue(1).ToString();
        //        logInfo.LogTime = DateTime.Now;

        //        logInfo.JCLSH = JCLSH;
        //        logInfo.Log_Infor = logMsg;
        //        logInfo.OpName = operatorName;
        //        logInfo.Name = logHelper.GetLogName(type);
        //        logInfo.FunName = funName;

        //        logHelper.WriteLog(logInfo);
        //        #endregion
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine(ex.Message);
        //    }
        //}

        /// <summary>
        /// 获取统计数据
        /// </summary>
        /// <param name="stratDate">开始时间</param>
        /// <param name="endDate">结束时间</param>
        /// <returns>返回datatable</returns>
        public DataTable GetSatisticsData(string stratDate, string endDate,string CheckType)
        {
            m_dbStoreProcedure = new DbStoredProcedure();
            DataTable dt = new DataTable();
            SqlParameter param = new SqlParameter("@startDate", stratDate);
            SqlParameter param1 = new SqlParameter("@EndDate", endDate);
            SqlParameter param2 = new SqlParameter("@CheckType", CheckType);
            SqlParameter[] sqlParams = new SqlParameter[] { param, param1 ,param2};

            m_dbStoreProcedure.GetProcDataTable(ref dt, "proc_RESULT_VEHICLE_INFO_GetJCXHData", sqlParams);

            dt.Columns.Add("InitPercent", typeof(string));
            dt.Columns.Add("FirstPercent", typeof(string));
            dt.Columns.Add("SecondPercent", typeof(string));
            dt.Columns.Add("OtherPercent", typeof(string));

            int initCount = 0, initCheckCount = 0, firstCount = 0, firstCheckCount = 0, secondCount = 0, secondCheckCount = 0, otherCount = 0, otherCheckCount = 0;

            foreach (DataRow dr in dt.Rows) {
                #region 统计行
                initCount += Convert.ToInt32(dr["InitialCheckNum"]);
                initCheckCount += Convert.ToInt32(dr["InitialCheckNumQualified"]);

                firstCount += Convert.ToInt32(dr["FirstReview"]);
                firstCheckCount += Convert.ToInt32(dr["FirstReviewQualified"]);

                secondCount += Convert.ToInt32(dr["SecondReview"]);
                secondCheckCount += Convert.ToInt32(dr["SecondReviewQualified"]);

                otherCount += Convert.ToInt32(dr["OtherReview"]);
                otherCheckCount += Convert.ToInt32(dr["OtherReviewQualified"]);
                #endregion

                if ((int)dr["InitialCheckNum"] > 0)
                {
                    dr["InitPercent"] = Convert.ToString((int)dr["InitialCheckNumQualified"] * 100 / (int)dr["InitialCheckNum"]) + "%";
                }
                else
                {
                    dr["InitPercent"] = "0%";
                }

                if ((int)dr["FirstReviewQualified"] > 0)
                {
                    dr["FirstPercent"] = Convert.ToString((int)dr["FirstReviewQualified"] * 100 / (int)dr["FirstReview"]) + "%";
                }
                else
                {
                    dr["FirstPercent"] = "0%";
                }

                if ((int)dr["SecondReviewQualified"] > 0)
                {
                    dr["SecondPercent"] = Convert.ToString((int)dr["SecondReviewQualified"] * 100 / (int)dr["SecondReview"]) + "%";
                }
                else
                {
                    dr["SecondPercent"] = "0%";
                }

                if ((int)dr["OtherReviewQualified"] > 0)
                {
                    dr["OtherPercent"] = Convert.ToString((int)dr["OtherReviewQualified"] * 100 / (int)dr["OtherReview"]) + "%";
                }
                else
                {
                    dr["OtherPercent"] = "0%";
                }

            }

            DataRow countDr = dt.NewRow();
            countDr["FirstReviewQualified"] = 0;
            countDr["SecondReviewQualified"] = 0;
            countDr["OtherReviewQualified"] = 0;


            countDr["JCXH"] = "合计";
            countDr["InitialCheckNum"] = initCount;
            countDr["InitialCheckNumQualified"] = initCheckCount;
            if (initCount > 0)
            {
                countDr["InitPercent"] = (initCheckCount * 100 / initCount).ToString() + "%";
            }
            else
            {
                countDr["InitPercent"] = "0%";
            }

            countDr["FirstReview"] = firstCount;
            if (firstCount > 0)
            {
                countDr["FirstPercent"] = (firstCheckCount * 100 / firstCount).ToString() + "%";
            }
            else
            {
                countDr["FirstPercent"] = "0%";
            }

            countDr["SecondReview"] = secondCount;
            if (secondCount > 0)
            {
                countDr["SecondPercent"] = (secondCheckCount * 100 / secondCount).ToString() + "%";
            }
            else
            {
                countDr["SecondPercent"] = "0%";
            }

            countDr["OtherReview"] = otherCount;
            if (otherCount > 0)
            {
                countDr["OtherPercent"] = (otherCheckCount * 100 / otherCount).ToString() + "%";
            }
            else
            {
                countDr["OtherPercent"] = "0%";
            }

            dt.Rows.Add(countDr);


            return dt;

        }

        /// <summary>
        /// 绑定数据到表格中
        /// </summary>
        /// <param name="startDate">开始时间</param>
        /// <param name="endDate">结束时间</param>
        private void BindDataToRptList(string startDate, string endDate)
        {
            try
            {
                DataTable dt = GetSatisticsData(startDate, endDate,m_checkType);
                rptList.DataSource = dt;
                rptList.DataBind();
            }
            catch (Exception ex)
            {

            }
        }

        private void SetSearchDate()
        {
            m_startDate = txtStart.Text;
            m_endDate = txtEnd.Text;

            //当条件为空的查询范围 加减100年
            DateTime dFuture = DateTime.Now.AddYears(100);
            DateTime dPast = DateTime.Now.AddYears(-100);

            //获取当前方法名称，写入日志
            string funName = string.Format("{0}.aspx.cs -> {1}", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name, (new StackTrace()).GetFrame(0).GetMethod().Name);
            // WriteLog(string.Empty, "查询安检检测线号数据",Session["UserName"].ToString(), LogHelper.LogType.Normal, funName);

            //获取表中的最大最小日期
            string maxDateSql = "SELECT TOP 1 JCRQ FROM RESULT_VEHICLE_INFO WHERE JCRQ IS NOT NULL ORDER BY JCRQ DESC";
            string minDateSql = "SELECT TOP 1 JCRQ FROM RESULT_VEHICLE_INFO WHERE JCRQ IS NOT NULL ORDER BY JCRQ ASC";
            string maxDate = DbHelper.GetValue(maxDateSql);
            string minDate = DbHelper.GetValue(minDateSql);

            if (txtStart.Text == string.Empty && txtEnd.Text == string.Empty)
            {
                m_endDate = dFuture.ToString("yyyy-MM-dd");
                m_startDate = dPast.ToString("yyyy-MM-dd");

                lblDate.Text = string.Format("{0} - {1}", minDate, maxDate);
            }
            else if (txtStart.Text == string.Empty)
            {
                m_startDate = dPast.ToString("yyyy-MM-dd");
                lblDate.Text = string.Format("{0} - {1}", minDate, m_endDate);
            }
            else if (txtEnd.Text == string.Empty)
            {
                m_endDate = dFuture.ToString("yyyy-MM-dd");
                lblDate.Text = string.Format("{0} - {1}", minDate, maxDate);
            }
            else
            {
                lblDate.Text = string.Format("{0} - {1}", m_startDate, m_endDate);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                SetSearchDate();
                BindDataToRptList(m_startDate, m_endDate);
            }
            catch (Exception ex)
            {

            }
        }

        protected void btnSearchAll_Click(object sender, EventArgs e)
        {
            try
            {
                txtStart.Text = string.Empty;
                txtEnd.Text = string.Empty;
                btnSearch_Click(null, null);
            }
            catch (Exception ex)
            {

            }

        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                gfAjaxJs.SetGoToUrl(this.UpdatePanel1, string.Format("/PrintAll/PrintAJ_JCXH.aspx?startdate={0}&enddate={1}&CheckType={2}", m_startDate, m_endDate,m_checkType));
            }
            catch (Exception ex)
            {
                gfAjaxJs.SetAlertMsg(this.UpdatePanel1, ex.Message);
            }
        }
    }
}